package org.edu.modules.dorm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.edu.modules.dorm.entity.*;
import org.edu.modules.dorm.entity.bo.BasicResponseBO;
import org.edu.modules.dorm.entity.bo.VeCampusBO;
import org.edu.modules.dorm.mapper.VeBaseCalendarMapper;
import org.edu.modules.dorm.mapper.VeDormSemesterMapper;
import org.edu.modules.dorm.mapper.VeDormWSceilMapper;
import org.edu.modules.dorm.service.*;
import org.edu.modules.dorm.vo.VeDormCalendarVo;
import org.edu.modules.dorm.vo.VeDormWsceilExcelVO;
import org.edu.modules.dorm.vo.VeDormWsceilVo;
import org.edu.modules.dorm.vo.VeFindStudentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class VeDormWsceilServiceImpl extends ServiceImpl<VeDormWSceilMapper, VeDormWsceil> implements VeDormWsceilService {
    @Resource
    private VeDormWSceilMapper veDormWSceilMapper;
    @Resource
    private VeBaseCalendarMapper veDormCalendarMapper;
    @Resource
    private VeDormSemesterMapper veDormSemesterMapper;

    @Autowired
    VeFindTFStudentService mVeFindTFStudentService ;
    @Autowired
    VeDormSuSheLouService mVeDormSuSheLouService ;
    @Autowired
    VeDormSuSheService mVeDormSuSheService ;
    @Autowired
    VeDormSemesterService veDormSemesterService ;
    @Autowired
    VeDormLoucengService mVeDormLoucengService ;

    @Resource
    private VeBaseDormManageService veBaseDormManageService;

    @Override
    public List<VeDormWsceilVo> queryWsceil(Long campusId, Long jzwId, Long lcId, Long ssId, Long semId, Long week) {
        return veDormWSceilMapper.queryWsceil(campusId, jzwId, lcId, ssId, semId, week);
    }

    @Override
    public VeDormCalendarVo findNowDate() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateNowStr = sdf.format(d);
        QueryWrapper<VeBaseCalendar> wrapper = new QueryWrapper<>();
        wrapper.eq("dates",dateNowStr);
        VeBaseCalendar veDormCalendar = veDormCalendarMapper.selectOne(wrapper);

        VeDormSemester veDormSemester = veDormSemesterMapper.selectById(veDormCalendar.getSemId());

        VeDormCalendarVo veDormCalendarVo = new VeDormCalendarVo();
        veDormCalendarVo.setId(veDormCalendar.getId());
        veDormCalendarVo.setSemId(veDormCalendar.getSemId());
        veDormCalendarVo.setDayOfWeek(veDormCalendar.getDayOfWeek());
        veDormCalendarVo.setMonth(veDormCalendar.getMonth());
        veDormCalendarVo.setXQMC(veDormSemester.getXQMC());
        veDormCalendarVo.setWeek(veDormCalendar.getWeek());
        return veDormCalendarVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(Long campusId, Long semId, Integer week, Long jzwId, Long lcId, Long ssId, List<Long> list,Long mouth) {
        Integer flag = 0;

        VeDormWsceil veDormWsceil1 = new VeDormWsceil();
        Long time =System.currentTimeMillis()/1000;
        veDormWsceil1.setAddTime(time);
        veDormWsceil1.setCampusId(campusId);
        veDormWsceil1.setJzwId(jzwId);
        veDormWsceil1.setLcId(lcId);
        veDormWsceil1.setSsId(ssId);
        veDormWsceil1.setWeek(7L);
        veDormWsceil1.setWeekNum(Long.valueOf(week));
        veDormWsceil1.setSemId(semId);
        veDormWsceil1.setMouth(mouth);
        flag += veDormWSceilMapper.insert(veDormWsceil1);

        VeDormWsceil veDormWsceil = new VeDormWsceil();
        veDormWsceil.setAddTime(time);
        veDormWsceil.setCampusId(campusId);
        veDormWsceil.setJzwId(jzwId);
        veDormWsceil.setLcId(lcId);
        veDormWsceil.setSsId(ssId);
        veDormWsceil.setSemId(semId);
        veDormWsceil.setWeekNum(Long.valueOf(week));
        veDormWsceil.setMouth(mouth);

        for (int i = 0; i <list.size() ; i++) {
            veDormWsceil.setWeek(i+1L);
            veDormWsceil.setScore(list.get(i));
            flag += veDormWSceilMapper.insert(veDormWsceil);
        }

        return flag == 6;
    }

    @Override
    public List<VeDormWsceil> updateMessage(Long id) {
        VeDormWsceil veDormWsceil = veDormWSceilMapper.selectById(id);
        QueryWrapper<VeDormWsceil> wrapper = new QueryWrapper<>();
        wrapper.eq("semId",veDormWsceil.getSemId());
        wrapper.eq("weekNum",veDormWsceil.getWeekNum());
        wrapper.eq("ssId",veDormWsceil.getSsId());
        List<VeDormWsceil> list = veDormWSceilMapper.selectList(wrapper);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(List<Long> idList, List<Long> scoreList) {
        Integer flag = 0;

        for (int i = 0; i <scoreList.size(); i++) {
            VeDormWsceil veDormWsceil = new VeDormWsceil();
            veDormWsceil.setScore(scoreList.get(i));
            veDormWsceil.setId(idList.get(i));
            flag +=veDormWSceilMapper.updateById(veDormWsceil);
        }

        return flag == 5;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(Long id) {
        List<VeDormWsceil> list = new ArrayList<>();
        VeDormWsceil veDormWsceil = veDormWSceilMapper.selectById(id);
        list.add(veDormWsceil);
        QueryWrapper<VeDormWsceil> wrapper = new QueryWrapper<>();
        wrapper.eq("semId",veDormWsceil.getSemId());
        wrapper.eq("weekNum",veDormWsceil.getWeekNum());
        List<VeDormWsceil> list2 = veDormWSceilMapper.selectList(wrapper);

        list.addAll(list2);
        Integer flag = 0;
        for (VeDormWsceil dormWsceil : list) {
            flag += veDormWSceilMapper.deleteById(dormWsceil.getId());
        }

        return flag == 6;
    }

    @Override
    public List<VeDormWsceilVo> allWsceil(Long ssId) {
        return veDormWSceilMapper.allWsceil(ssId);
    }

    @Override
    public Integer findWsceil(Long semId, Integer weekNum, Long ssId) {
        return veDormWSceilMapper.checkWsceil(semId, weekNum, ssId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int excelImport(List<VeDormWsceilExcelVO> list) throws Exception{
        List<VeDormWsceil> result0 = new ArrayList<>();
        //获取所有校区信息
        BasicResponseBO<List> bo = veBaseDormManageService.getCampusMessage(); //李少君
        List<VeCampusBO> result = JSONObject.parseArray(JSON.toJSONString(bo.getResult()),VeCampusBO.class);
        List<VeFindStudentVo> bo1 = new ArrayList<>();
        for(int i =0 ;i<result.size();i++){
            VeFindStudentVo c = new VeFindStudentVo();
            c.setId(result.get(i).getId());
            c.setName(result.get(i).getXqmc());
            bo1.add(c);
        }
        //获取所有宿舍楼信息
        List<VeDormSSLou> sushelou = mVeDormSuSheLouService.list() ;
        // 获取所有楼层
        List<VeDormLouceng> lc= mVeDormLoucengService.list() ;


        // 获取所有宿舍信息
        List<VeDormSuShe> sushe = mVeDormSuSheService.list() ;
        // 学期信息
        BasicResponseBO<List> list1 = veBaseDormManageService.getSemesterMessage();//李少君
        List<VeDormSemester> result1 = JSONObject.parseArray(JSON.toJSONString(list1.getResult()),VeDormSemester.class);

        Long time = System.currentTimeMillis()/1000;
        for(int i =0;i<list.size();i++){
            VeDormWsceil sceil = new VeDormWsceil();
            sceil.setAddTime(time).setScore(list.get(i).getScore())
                    .setMouth(list.get(i).getMouth()).setWeekNum(list.get(i).getWeekNum()).setWeek(list.get(i).getWeek())
                    .setTerminalId(1L);
            for (int j = 0; j < result1.size(); j++) {
                if (result1.get(j).getXQMC().equals(list.get(i).getSemId())) {
                    sceil.setSemId(result1.get(j).getId().longValue());
                }
            }
            for (int k = 0; k < bo1.size(); k++) {
                if (bo1.get(k).getName().equals(list.get(i).getCampusId())) {
                    sceil.setCampusId(bo1.get(k).getId());
                }
            }
            for (int a = 0; a < sushelou.size(); a++) {
                if (sushelou.get(a).getJzwmc().equals(list.get(i).getJzwId())) {
                    sceil.setJzwId(sushelou.get(a).getId().longValue());
                }
            }
            for (int b = 0; b < lc.size(); b++) {
                if(lc.get(b).getLcname().equals(list.get(i).getLcId())){
//                    sceil.setLcId(lc.get(b).getId().longValue());
                    sceil.setLcId(mVeDormLoucengService.getLoucengId(sceil.getJzwId().intValue(),lc.get(b).getLcname()));
                }
            }
            for (int c = 0; c < sushe.size(); c++) {
                if(sushe.get(c).getFJBM().equals(list.get(i).getSsId())){
                    sceil.setSsId(sushe.get(c).getId());
                }
            }
            List<VeDormWsceil> queryWs = veDormWSceilMapper.Wsceil(sceil.getSemId(), sceil.getCampusId(), sceil.getJzwId(),
                    sceil.getLcId(), sceil.getSsId(), sceil.getMouth(), sceil.getWeekNum(), sceil.getWeek());
            if(queryWs != null){
                return -1;
            }
            if(sceil.getSemId()==null || sceil.getCampusId()==null || sceil.getJzwId()==null ||sceil.getLcId()==null || sceil.getSsId()==null){
                return 0;
            }

            veDormWSceilMapper.insert(sceil) ;

        }

        return 1;

    }




//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void excelImport(List<VeDormWsceilExcelVO> list) throws Exception {
//        // 获取所有校区信息
//        List<VeFindStudentVo> xiaoqu =  mVeFindTFStudentService.findXiaoQu() ;
//        Map<String,Long> map = new HashMap<>() ;
//        xiaoqu.forEach(l-> map.put(l.getName(),l.getId()));
//        // 获取所有宿舍楼信息
//        List<VeDormSSLou> sushelou = mVeDormSuSheLouService.list() ;
//        Map<Long,List<VeDormSSLou>> groupXiaoqu = sushelou.stream().collect(Collectors.groupingBy(VeDormSSLou::getXqh)) ;
//        Map<Long,Map<String,Integer>> sushelouMap = new HashMap<>() ;
//        groupXiaoqu.forEach((k,v)->{
//            Map<String,Integer> c = new HashMap<>() ;
//            v.forEach(l-> c.put(l.getJzwmc(),l.getId()));
//            sushelouMap.put(k,c) ;
//        });
//        // 获取所有楼层
//        List<VeDormLouceng> lc= mVeDormLoucengService.list() ;
//        Map<Integer,List<VeDormLouceng>> groupSushelou = lc.stream().collect(Collectors.groupingBy(VeDormLouceng::getJzwh)) ;
//        Map<Integer,Map<String,Integer>> lcMap = new HashMap<>() ;
//        groupSushelou.forEach((k,v)->{
//            Map<String,Integer> c = new HashMap<>() ;
//            v.forEach(l-> c.put(l.getLcname(),l.getId()));
//            lcMap.put(k,c) ;
//        });
//        // 获取所有宿舍信息
//        List<VeDormSuShe> sushe = mVeDormSuSheService.list() ;
//        Map<Long,List<VeDormSuShe>> groupLc = sushe.stream().collect(Collectors.groupingBy(VeDormSuShe::getLCH)) ;
//        Map<Long,Map<String,Long>> susheMap = new HashMap<>() ;
//        groupLc.forEach((k,v)->{
//            Map<String,Long> c = new HashMap<>() ;
//            v.forEach(l-> c.put(l.getFJBM(),l.getId()));
//            susheMap.put(k,c) ;
//        });
//        // 学期信息
//        List<VeDormSemester> semester = veDormSemesterService.list();
//        Map<String,Long> semesterMap = new HashMap<>() ;
//        semester.forEach(l-> semesterMap.put(l.getXQMC(),l.getId()));
//
//        Long time = System.currentTimeMillis()/1000;
//        int t = 4 ;
//        try{
//            for ( VeDormWsceilExcelVO ve : list) {
//                VeDormWsceil sceil = new VeDormWsceil() ;
//                BeanUtils.copyProperties(ve,sceil);
//                // 获取学期信息
//                Long sem = semesterMap.get(ve.getSemId()) ;
//                // 获取校区信息
//                Long xiaoquId = map.get(ve.getCampusId()) ;
//                // 宿舍楼
//                Integer lou = sushelouMap.get(xiaoquId).get(ve.getJzwId()) ;
//                // 楼层
//                Integer lcId = lcMap.get(lou).get(ve.getLcId()) ;
//                //宿舍
//                Long susheId = susheMap.get(Long.parseLong(lcId+"")).get(ve.getSsId()) ;
//                sceil.setAddTime(time).setCampusId(xiaoquId).setJzwId(Long.parseLong(lou+""))
//                        .setLcId(Long.parseLong(lcId+"")).setSsId(susheId)
//                        .setTerminalId(1L).setSemId(sem);
//                veDormWSceilMapper.insert(sceil) ;
//                t++ ;
//            }
//        }catch (Exception e){
//            throw new Exception("第"+t+"行数据有误！") ;
//        }
//    }

}
